$(document).ready(function() {
	var $form = $(document.forms[0]);
	var $widgets = $form.find("input,textarea,select");

	var data = {
		rules : {},
		messages : {}
	};

	$widgets.each(function() {
		try {
			var _validator = $.parseJSON($(this).attr("validator"));
			var _rule = _validator.rule;
			var _message = _validator.message;
			data.rules[$(this).attr("name")] = _rule;
			data.messages[$(this).attr("name")] = _message;
		} catch (e) {

		}
	});

	$form.validate(data);

	var $table = $("select[table='true']");
	if ($table[0]) {
		var selection = $table.attr("selection");
		for ( var key in screeners) {
			var option = document.createElement("option");
			var $option = $(option);
			$option.html(key).val(key);
			if (key == selection) {
				$option.attr("selected", "selected");
			}
			$table.append(option);
		}
	}

	var $pairs = $("button[pair='true']");
	$pairs.each(function() {
		var $pair = $(this);
		var bys = $pair.attr("bys");
		var orders = $pair.attr("orders");
		if (bys && bys != 'null' && bys != '' && orders && orders != 'null' && orders != '') {
			var arr1 = bys.substring(1, bys.length - 1).split(",");
			var arr2 = orders.substring(1, orders.length - 1).split(",");
			for ( var i = 0; i < arr1.length; i++) {
				addOrderPair($pair, arr1[i], arr2[i]);
			}
		}
	});

	var $properties = $("button[property='true']");
	$properties.each(function() {
		var $property = $(this);
		var properties = $property.attr("properties");
		if (properties && properties != 'null' && properties != '') {
			var arr = properties.substring(1, properties.length - 1).split(",");
			for ( var i = 0; i < arr.length; i++) {
				addProperty($property, arr[i]);
			}
		}
	});

});

function addProperty(button, property) {
	var $button = $(button);

	var container = $button.attr("container");
	var table = $button.attr("table");
	var _data = $.parseJSON($button.attr("data"));

	var $select = $(document.createElement("select"));
	if (_data.id) {
		$select.attr("id", _data.id);
	}
	if (_data.name) {
		$select.attr("name", _data.name);
	}
	if (_data.clazz) {
		$select.attr("class", _data.clazz);
	}
	if (_data.style) {
		$select.attr("style", _data.style);
	}

	var properties = screeners[$("select[name='" + table + "']").val()];

	for ( var i = 0; properties && i < properties.length; i++) {
		var _property = properties[i];

		var $option = $(document.createElement("option"));
		$option.html(_property.display).val(_property.name);
		if (_property.name == property) {
			$option.attr("selected", "selected");
		}

		$select.append($option[0]);
	}

	var $remove = $(document.createElement("button"));
	$remove.html("删除");

	var $br = $(document.createElement("br"));

	$("#" + container).append($select[0]).append($remove[0]).append($br[0]);

	$remove.click(function() {
		$select.remove();
		$remove.remove();
		$br.remove();
	});
}

function openScreener(button) {
	var $button = $(button);

	var table = $button.attr("table");
	var name = $button.attr("name");
	var $container = $('<div id="filter-container"></div>').width(360).height(120).hide();

	var key = $("select[name='" + table + "']").val();
	var $filter = $container.ligerFilter({
		fields : screeners[key]
	});

	try {
		$filter.setData($.parseJSON($("textarea[name='" + name + "']").val()));
	} catch (e) {
	}

	window.screener = $.ligerDialog.open({
		width : 560,
		height : 320,
		title : '筛选器',
		target : $container,
		isResize : true,
		top : 50,
		buttons : [ {
			text : '确定',
			onclick : function(item, dialog) {
				var object = $filter.getData();
				var condition = $.ligerui.toJSON(object);
				$("textarea[name='" + name + "']").val(condition);
				dialog.close();
			}
		}, {
			text : '取消',
			onclick : function(item, dialog) {
				dialog.close();
			}
		} ]
	});
}

function openSelector(url, name) {
	$.ligerDialog.open({
		url : url,
		title : '选择器',
		width : 1024,
		height : 480,
		isResize : false,
		slide : true,
		buttons : [ {
			text : '确定',
			onclick : function(item, dialog) {
				var $form = $(dialog.frame.document.forms[0]);
				var $table = $form.find("table");
				var $checkeds = $table.find("input[type='checkbox']:checked,input[type='radio']:checked");
				if ($checkeds.length == 0) {
					$.ligerDialog.alert('请选择一条记录!');
					return;
				} else if ($checkeds.length > 1) {
					$.ligerDialog.alert('只能选择一条记录!');
					return;
				} else {
					$("input[name='" + name + "']").val($($checkeds[0]).val());
					dialog.close();
				}
			}
		}, {
			text : '清空',
			onclick : function(item, dialog) {
				$("input[name='" + name + "']").val('');
				dialog.close();
			}
		}, {
			text : '关闭',
			onclick : function(item, dialog) {
				dialog.close();
			}
		} ]
	});
}

function addInputOption(container, label, name, value, style, validator) {
	var $container = $("#" + container);
	var div = document.createElement("div");
	var $div = $(div);
	var input = document.createElement("input");
	var $input = $(input);
	var remove = document.createElement("button");
	var $remove = $(remove);
	$remove.text("删除");
	$remove.click(function() {
		$div.remove();
	});
	$input.attr("type", "text").attr("name", name).val(value).attr("style", style).attr("validator", validator);
	$div.append(label);
	$div.append(":");
	$div.append(" ");
	$div.append(input);
	$div.append(" ");
	$div.append(remove);
	$container.append(div);
	return input;
}

function addOrderPair(button, property, sequence) {
	var table = $(button).attr("table");
	var container = $(button).attr("container");

	var _by = $.parseJSON($(button).attr("by"));
	var _order = $.parseJSON($(button).attr("order"));

	var $select = $(document.createElement("select"));
	if (_by.id) {
		$select.attr("id", _by.id);
	}
	if (_by.name) {
		$select.attr("name", _by.name);
	}
	if (_by.clazz) {
		$select.attr("class", _by.clazz);
	}
	if (_by.style) {
		$select.attr("style", _by.style);
	}

	var properties = screeners[$("select[name='" + table + "']").val()];

	for ( var i = 0; properties && i < properties.length; i++) {
		var _property = properties[i];

		var $option = $(document.createElement("option"));
		$option.html(_property.display).val(_property.name);
		if (property && property == _property.name) {
			$option.attr("selected", "selected");
		}

		$select.append($option[0]);
	}

	var $order = $(document.createElement("select"));
	if (_order.id) {
		$order.attr("id", _order.id);
	}
	if (_order.name) {
		$order.attr("name", _order.name);
	}
	if (_order.clazz) {
		$order.attr("class", _order.clazz);
	}
	if (_order.style) {
		$order.attr("style", _order.style);
	}
	var $asc = $(document.createElement("option"));
	$asc.val("ASC").html("升序");
	var $desc = $(document.createElement("option"));
	$desc.val("DESC").html("降序");
	if (sequence && sequence == "ASC") {
		$asc.attr("selected", "selected");
	} else if (sequence && sequence == "DESC") {
		$desc.attr("selected", "selected");
	}
	$order.append($asc[0]).append($desc[0]);

	var $remove = $(document.createElement("button"));
	$remove.html("删除");

	var $br = $(document.createElement("br"));
	$("#" + container).append($select[0]).append($order[0]).append($remove[0]).append($br[0]);
	$remove.click(function() {
		$select.remove();
		$order.remove();
		$remove.remove();
		$br.remove();
	});
}

function replace(textarea, imageUploadURL) {
	CKEDITOR.replace(textarea, addUploadButton(this));
	function addUploadButton(editor) {
		CKEDITOR.on('dialogDefinition', function(ev) {
			var dialogName = ev.data.name;
			var dialogDefinition = ev.data.definition;
			if (dialogName == 'image') {
				var infoTab = dialogDefinition.getContents('info');
				infoTab.add({
					type : 'button',
					id : 'upload_image',
					align : 'center',
					label : '上传并使用本地图片',
					onClick : function(evt) {
						var thisDialog = this.getDialog();
						var txtUrlObj = thisDialog.getContentElement('info', 'txtUrl');
						var txtUrlId = txtUrlObj.getInputElement().$.id;
						addUploadImage(txtUrlId);
					}
				}, 'browse'); // place front of the browser button
			}
		});
	}
	function addUploadImage(theURLElementId) {
		var uploadUrl = imageUploadURL; // 这是我自己的处理文件/图片上传的页面URL
		var imgUrl = window.showModalDialog(uploadUrl, null, "dialogWidth=500px;dialogHeight=200px;status=no;");
		// 在upload结束后通过js代码window.returnValue=...可以将图片url返回给imgUrl变量。
		// 更多window.showModalDialog的使用方法参考
		var urlObj = document.getElementById(theURLElementId);
		urlObj.value = imgUrl;
		// urlObj.fireEvent("onchange"); //触发url文本框的onchange事件，以便预览图片
		$(urlObj).change();
	}
}

function openImageUploader(url, type_acceptor, path_acceptor, size_acceptor) {
	$.ligerDialog.open({
		url : url,
		title : '文件上传器',
		width : 500,
		height : 200,
		buttons : [ {
			text : '确定',
			onclick : function(item, dialog) {
				try {
					var data = dialog.frame.getData();
					$find("input[name=" + type_acceptor + "]").val(data.type);
					$find("input[name=" + path_acceptor + "]").val(data.path);
					$find("input[name=" + size_acceptor + "]").val(data.size);
				} catch (e) {
					$.ligerDialog.warn("还没上传文件");
				} finally {
					dialog.close();
				}
			}
		}, {
			text : '关闭',
			onclick : function(item, dialog) {
				dialog.close();
			}
		} ]
	});
}